//
//  YBTakeSameVideoVC.m
//  WuyouTang
//
//  Created by YB007 on 2019/11/27.
//  Copyright © 2019 cat. All rights reserved.
//

#import "YBTakeSameVideoVC.h"

#import "VideoCollectionCell.h"
#import "NearbyVideoModel.h"
#import "YBLookVideoVC.h"
#import "TCVideoRecordViewController.h"
#import "YBGetVideoObj.h"

@interface YBTakeSameVideoVC ()<UICollectionViewDelegate,UICollectionViewDataSource,NSURLConnectionDelegate,NSURLConnectionDataDelegate>
{
    int _paging;
    NSMutableData *musicData;
    long long allLength;
    float currentLength;
}
@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,strong)UIImageView *bgImgView;
@property(nonatomic,strong)UIView *effectView;
@property(nonatomic,strong)UIImageView *musicIV;
@property(nonatomic,strong)UILabel *musicNameL;
@property(nonatomic,strong)UILabel *musicAuthorL;
@property(nonatomic,strong)UILabel *musicUsesL;

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,strong)UIButton *sameBtn;

@end

@implementation YBTakeSameVideoVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self pullData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.subNavi.backgroundColor = UIColor.clearColor;
    self.dataArray = [NSMutableArray array];
    _paging = 1;
    
    [self.view addSubview:self.collectionView];
    if (@available(iOS 11.0,*)) {
        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.sameBtn];
    
    [_sameBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(70);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-ShowDiff-34);
    }];
    
    [self.view bringSubviewToFront:self.naviView];
    
}
-(void)pullData {
    
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Video.getVideoListByMusic" Dic:@{@"p":@(_paging),@"musicid":minstr([_musicDic valueForKey:@"id"])} Suc:^(int code, id info, NSString *msg) {
        [_collectionView.mj_footer endRefreshing];
        [_collectionView.mj_header endRefreshing];
        if (code == 0) {
            NSDictionary *infoDic = [info firstObject];
            NSDictionary *music_dic = [infoDic valueForKey:@"musicinfo"];
            if (_paging == 1) {
                [_dataArray removeAllObjects];
                [_musicIV sd_setImageWithURL:[NSURL URLWithString:minstr([music_dic valueForKey:@"img_url"])]];
                [_bgImgView sd_setImageWithURL:[NSURL URLWithString:minstr([music_dic valueForKey:@"img_url"])]];
                _musicNameL.text = minstr([music_dic valueForKey:@"title"]);
                _musicAuthorL.text = minstr([music_dic valueForKey:@"author"]);
                _musicUsesL.text = minstr([music_dic valueForKey:@"use_nums"]);
            }
            NSArray *listA = [infoDic valueForKey:@"videolist"];
            if (listA.count<=0) {
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [_dataArray addObjectsFromArray:listA];
            }
            if (_dataArray.count <= 0) {
                [PublicView showTextNoData:_collectionView text1:@"" text2:YZMsg(@"暂无视频哦~") centerY:0.8];
            }else {
                [PublicView hiddenTextNoData:_collectionView];
            }
            [_collectionView reloadData];
            
        }else {
            [MBProgressHUD showError:msg];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    } Fail:^(id fail) {
        [_collectionView.mj_footer endRefreshing];
               [_collectionView.mj_header endRefreshing];
    }];
   
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat moveY = scrollView.contentOffset.y < 0 ? 0 : scrollView.contentOffset.y;
    
    _sameBtn.bottom = _window_height-ShowDiff-34+moveY;
    
    NSLog(@"ssss=%f",scrollView.contentOffset.y);
}
#pragma mark - CollectionView 代理
/*
 * minimumLineSpacing、minimumInteritemSpacing去设置
 -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
 return CGSizeMake(0,0);
 }
 -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
 {
 return UIEdgeInsetsMake(0,0,0,0);
 }
 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YBTackSameHeader" forIndexPath:indexPath];
        [reusableView addSubview:self.headerView];
        return reusableView;
    }
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(_window_width, 120+64+statusbarHeight);
}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
//    return 0.01;
//}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//    return 0.01;
//}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    VideoCollectionCell *cell = (VideoCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"VideoCollectionCell" forIndexPath:indexPath];
    NSDictionary *subdic = _dataArray[indexPath.row];
    cell.isTakeSameList = YES;
    cell.model = [[NearbyVideoModel alloc] initWithDictionary:subdic];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *vidoeID = minstr([_dataArray[indexPath.row] valueForKey:@"id"]);
    [YBGetVideoObj lookManeger].fromWhere = @"YBTakeSameVideoVC";
    [YBGetVideoObj lookManeger].videoID = vidoeID;
    [YBGetVideoObj lookManeger].playIndex = (int)indexPath.row;
    [YBGetVideoObj lookManeger].videoList = [_dataArray mutableCopy];
    [YBGetVideoObj lookManeger].paging = _paging;
    NSString *basUrl = [NSString stringWithFormat:@"Video.getVideoListByMusic&musicid=%@",[_musicDic valueForKey:@"id"]];
    [YBGetVideoObj lookManeger].baseUrl = basUrl;
    [[YBGetVideoObj lookManeger]goLookVC];
}

#pragma mark - set/get
- (UIView *)effectView {
    if (!_effectView) {
        if (@available(iOS 8.0, *)) {
            UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
            _effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
        } else {
            UIToolbar *effectView = [[UIToolbar alloc] init];
            effectView.barStyle = UIBarStyleBlackTranslucent;
            _effectView = effectView;
        }
    }
    return _effectView;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake((_window_width-2)/3, (_window_width-2)/3 * 1.4);
        flow.minimumLineSpacing = 1;
        flow.minimumInteritemSpacing = 1;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, _window_width, _window_height) collectionViewLayout:flow];
        [_collectionView registerNib:[UINib nibWithNibName:@"VideoCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"VideoCollectionCell"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YBTackSameHeader"];
        _collectionView.delegate =self;
        _collectionView.dataSource = self;
        _collectionView.mj_footer  = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            _paging ++;
            [self pullData];
        }];
        
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _paging = 1;
            [self pullData];
            
        }];
        _collectionView.contentInset = UIEdgeInsetsMake(0, 0, ShowDiff, 0);
        _collectionView.backgroundColor = Normal_Color;
    }
    return _collectionView;
}
- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 120+64+statusbarHeight)];
        _headerView.backgroundColor = RGB_COLOR(@"#eeeeee", 1);
        
        _bgImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _headerView.width, _headerView.height)];
        [_headerView addSubview:_bgImgView];
        [_bgImgView addSubview:self.effectView];
        [_effectView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.centerX.centerY.equalTo(_bgImgView);
        }];
        
        _musicIV = [[UIImageView alloc]init];
        _musicIV.layer.cornerRadius = 5;
        _musicIV.layer.masksToBounds = YES;
        [_headerView addSubview:_musicIV];
        [_musicIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_headerView.mas_left).offset(15);
            make.top.equalTo(_headerView.mas_top).offset(10+64+statusbarHeight);
            make.width.height.mas_equalTo(100);
        }];
        //2.作者名称
        _musicAuthorL = [[UILabel alloc]init];
        _musicAuthorL.font = SYS_Font(13);
        _musicAuthorL.textColor = RGB_COLOR(@"#969696", 1);
        [_headerView addSubview:_musicAuthorL];
        [_musicAuthorL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_musicIV);
            make.left.equalTo(_musicIV.mas_right).offset(12);
            make.right.lessThanOrEqualTo(_headerView.mas_right).offset(-15);
        }];
        //1.音乐名称
        _musicNameL = [[UILabel alloc]init];
        _musicNameL.font = [UIFont boldSystemFontOfSize:17];
        _musicNameL.textColor = RGB_COLOR(@"#ffffff", 1);
        [_headerView addSubview:_musicNameL];
        [_musicNameL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_musicAuthorL.mas_top).offset(-8);
            make.left.equalTo(_musicAuthorL);
            make.right.lessThanOrEqualTo(_headerView.mas_right).offset(-15);
        }];
        //3.使用人数
        _musicUsesL = [[UILabel alloc]init];
        _musicUsesL.font = SYS_Font(10);
        _musicUsesL.textColor = RGB_COLOR(@"#969696", 1);
        [_headerView addSubview:_musicUsesL];
        [_musicUsesL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_musicAuthorL.mas_bottom).offset(8);
            make.left.equalTo(_musicAuthorL);
            make.right.lessThanOrEqualTo(_headerView.mas_right).offset(-15);
        }];
        
    }
    return _headerView;
}
- (UIButton *)sameBtn {
    if (!_sameBtn) {
        _sameBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [_sameBtn setImage:[UIImage imageNamed:getImagename(@"视频-拍同款")] forState:0];
        [_sameBtn addTarget:self action:@selector(clickSameBtn) forControlEvents:UIControlEventTouchUpInside];
        _sameBtn.backgroundColor = UIColor.clearColor;
    }
    return _sameBtn;
}

-(void)clickSameBtn {
    
    if ([[Config getOwnID] intValue] <= 0) {
        [PublicObj warnLogin];
        return;
    }
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (0 < app.allUploadPro && app.allUploadPro < 1) {
        [MBProgressHUD showPop:YZMsg(@"视频发布中，暂不支持操作")];
        return;
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *loadPath = [docDir stringByAppendingFormat:@"/*%@*%@*%@*%@.mp3",minstr([_musicDic valueForKey:@"title"]),minstr([_musicDic valueForKey:@"author"]),minstr([_musicDic valueForKey:@"length"]),minstr([_musicDic valueForKey:@"id"])];
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:loadPath]) {
        //已下载
        [self goVideoRecord:loadPath];
    }else{
        //下载歌曲
        [self musicDownLoad];
    }
    
}

-(void)goVideoRecord:(NSString *)localPath {
    
    [MBProgressHUD showMessage:@""];
    YBWeakSelf;
    //wyt_vip
    [WYNetworking postWithUrl:@"User.checkLiveVipStatus" Dic:nil Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            NSDictionary *dic = [info firstObject];
            [YBPower saveUnified:dic];
            [weakSelf judgeCanGoTake:localPath];
        }else {
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
}

-(void)judgeCanGoTake:(NSString *)localPath {
    NSString *videoLimit = minstr([YBPower getVideoStatus]);
    NSString *videoMsg = minstr([YBPower getVideoMsg]);
    if ([videoLimit isEqual:@"1"]) {
        TCVideoRecordViewController *video = [[TCVideoRecordViewController alloc]init];
        video.haveBGM = YES;
        video.musicPath = localPath;
        video.musicID = minstr([_musicDic valueForKey:@"id"]);
        video.isTakeSame = YES;
        video.recordType = RecordType_Normal;
        [[YBBaseAppDelegate sharedAppDelegate] pushViewController:video animated:YES];
    }else {
        [MBProgressHUD showPop:videoMsg];
    }
}


#pragma mark - 下载

-(void)musicDownLoad{
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showMessage:@""];
    });
    //下载
    NSURL *url = [NSURL URLWithString:minstr([_musicDic valueForKey:@"file_url"])];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.allHTTPHeaderFields = @{@"referer":h5url};
    [NSURLConnection connectionWithRequest:request delegate:self];
}
//接收到服务器响应的时候开始调用这个方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    musicData = [NSMutableData data];
    allLength = [response expectedContentLength];//返回服务器链接数据的有效大小
}
//开始进行数据传输的时候执行这个方法
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    [musicData appendData:data];
    currentLength += data.length;
    NSString *string = [NSString stringWithFormat:@"%.f%%",(currentLength/allLength)*100];
    
}
//数据传输完成的时候执行这个方法
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"已经完成数据的接收-------------");
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
    });
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *boxPath = [docDir stringByAppendingFormat:@"/*%@*%@*%@*%@.mp3",minstr([_musicDic valueForKey:@"title"]),minstr([_musicDic valueForKey:@"author"]),minstr([_musicDic valueForKey:@"length"]),minstr([_musicDic valueForKey:@"id"])];
    if([musicData writeToFile:boxPath atomically:YES]){
        NSLog(@"保存成功");
        //下载事件
        [self goVideoRecord:boxPath];
    }else{
        //下载事件
        [MBProgressHUD showError:YZMsg(@"音乐获取失败")];
        NSLog(@"保存失败");
    }
    
}
//数据传输错误的时候执行这个方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"请求错误的时候  %@",[error localizedDescription]);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
    });
    //下载事件
    [MBProgressHUD showError:YZMsg(@"音乐获取失败")];
    NSLog(@"保存失败");
}




@end
